package com.coffeeloversupportlibrary.coffeelover.mercury.game;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.coffeeloversupportlibrary.R;
import com.coffeeloversupportlibrary.coffeelover.mercury.entity.Game;
import com.coffeeloversupportlibrary.coffeelover.mercury.entity.User;
import com.coffeeloversupportlibrary.coffeelover.mercury.utils.HttpUtils;
import com.coffeeloversupportlibrary.coffeelover.mercury.utils.JsonUtils;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * @author 盛守义
 * @createTime 2021/11/26 21:36
 * @projectName TurningCoffee
 * @className ThirdStageActivity.java
 * @description TODO
 */
public class ThirdStageActivity extends AppCompatActivity {
    private static int maxWidth = 354;

    private SharedPreferences userInfo;
    private Activity activity = ThirdStageActivity.this;
    private User user;
    private Game game;

    private TextView tv_username, tv_coffeename, tv_introduce, tv_totalwater, tv_bar;
    private ImageView iv_towBar;
    private FrameLayout fl_water;

    private HttpUtils httpUtils = new HttpUtils();
    private JsonUtils jsonUtils = new JsonUtils();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.game_activity_bean);

        initView();
        setListener();
        setView();
    }

    void setView(){
        tv_username.setText(user.getData().getUser().getUserNickname());
        tv_coffeename.setText(game.getData().getTree().getTreeName());
        tv_totalwater.setText(""+game.getData().getTree().getUserWater());

        double proportion = (double) ((100-game.getData().getTree().getTreeWater())/0.4);
        tv_introduce.setText("阿拉比卡豆再浇水"+ String.format("%.2f", proportion) +"%嫩芽就长高啦! ");

        ViewGroup.LayoutParams params = tv_bar.getLayoutParams();
        params.width = (maxWidth/4)*((game.getData().getTree().getTreeWater()-60)/10);
        tv_bar.setLayoutParams(params);
    }

    void setListener(){
        BeanOnClickListener listener = new BeanOnClickListener();
        iv_towBar.setOnClickListener(listener);
        fl_water.setOnClickListener(listener);
    }

    void initView(){
        userInfo = getSharedPreferences("user", 0);
        user = jsonUtils.getUser(userInfo.getString("userInfo", ""));
        game = jsonUtils.getGame(userInfo.getString("tree", ""));

        tv_totalwater = findViewById(R.id.tv_totalwater);
        tv_coffeename = findViewById(R.id.tv_snamegb);
        tv_username = findViewById(R.id.tv_unamegb);
        tv_introduce = findViewById(R.id.tv_introducegb);
        tv_bar = findViewById(R.id.tv_bargb);

        fl_water = findViewById(R.id.fl_watergb);
        iv_towBar = findViewById(R.id.iv_towatergb);
    }

    class BeanOnClickListener implements View.OnClickListener{
        @Override
        public void onClick(View view) {
            switch (view.getId()){
                case R.id.iv_towatergb:
                    startActivity(new Intent(activity, GetWaterBarActivity.class));
                    break;
                case R.id.fl_watergb:
                    game = jsonUtils.getGame(userInfo.getString("tree", ""));
                    if(game.getData().getTree().getUserWater() >= 10){
                        WaterTree();
                    }else{
                        Toast.makeText(activity, "您的水滴不足，快去领取水滴吧", Toast.LENGTH_SHORT).show();
                    }
                    break;
            }
        }
    }

    void WaterTree(){
        Call call = httpUtils.getCall("/tree/water/"+game.getData().getTree().getId());
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(activity, "网络连接崩溃了，绝对绝对不是我们的错", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String res = response.body().string();
                Log.e("浇水", "onResponse: "+res);
                Game waterGame = jsonUtils.getGame(res);
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        SharedPreferences.Editor editor = userInfo.edit();
                        editor.putString("tree", res);
                        editor.commit();

                        ViewGroup.LayoutParams params = tv_bar.getLayoutParams();
                        params.width = params.width+maxWidth/3;
                        tv_bar.setLayoutParams(params);

                        tv_totalwater.setText(""+waterGame.getData().getTree().getUserWater());
                        float waterproportion = (float) ((100-waterGame.getData().getTree().getTreeWater())/0.4);
                        tv_introduce.setText("阿拉比卡豆再浇水"+ String.format("%.2f", waterproportion) +"%嫩芽就长高啦! ");
                        if(waterGame.getData().getTree().getTreeStatus() == 0){
                            AlertDialog alertDialog = new AlertDialog.Builder(activity)
                                    .setTitle("恭喜").setMessage("您获得了 "+waterGame.getMessage()+" 颗咖啡豆，可在商城兑换商品")
                                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialogInterface, int i) {
                                            startActivity(new Intent(activity, GameStartActivity.class));
                                            finish();
                                        }
                                    })
                                    .create();
                            alertDialog.show();
//                            startActivity(new Intent(activity, SecondStageActivity.class));
//                            finish();
                        }

                    }
                });
            }
        });
    }

    protected void onResume() {
        super.onResume();
        Log.e("返回时运行", "onResume: 返回了");
        game = jsonUtils.getGame(userInfo.getString("tree", ""));
        tv_totalwater.setText(""+game.getData().getTree().getUserWater());
    }
}
